<?php


namespace App\Controller;

use App\Model\ProductSku;
use App\Model\User;
use Asf\Database\RedisPool;
use Asf\Http\JsonResponse;
use Asf\Http\RedirectResponse;
use Asf\Http\Request;
use Asf\Http\Response;
use Asf\MessageQueue\MessageProducer;
use Asf\Support\Env;
use Asf\Util\Context;
use Swoole\Coroutine;

class IndexController
{
    public function index(Request $request)
    {
        $users = ProductSku::where('id',1)->get()->toArray();
        $arr = [];
        foreach ($users as $k => $v){
            $arr[$v['sku1']][] = ['id'=>$v['id'],'unique_num'=>$v['unique_num'],'sku1'=>$v['sku1'], 'sku2'=>$v['sku2'], 'price'=>$v['price']];
        }
        echo '输出';
        return new JsonResponse([
            'result' => $arr
        ]);
    }

    public function two(Request $request)
    {
        $users = User::where('id',2)->get()->toArray();
        return new JsonResponse([
            'result' => $users,
            'code' => 1
        ]);
    }
    //创建页面
    public function create(Request $request, RedisPool $redisPool, MessageProducer $messageProducer)
    {
        $data = [];

        //创建队列生产者，可延迟
        go(function () use ($messageProducer, $data){
            $messageProducer->delay('miaosha', json_encode(['id'=>rand(1, 99999), 'shop_id'=>20]),time()+rand(5,25));
        });
        return new JsonResponse(['msg'=>'邮件发送成功'], 305);
    }

    //创建操作
    public function store(Request $request)
    {
        $user = new User();
        $user->name = $request->get('name');
        $user->password = $request->get('password');
        $user->age = $request->get('age');

        $user->save();

        return new RedirectResponse('/user');
    }

    //编辑页面
    public function edit(Request $request, $id)
    {
        $user = User::find($id);

        return view('edit.html', ['user' => $user]);
    }

    //编辑操作
    public function update(Request $request, $id)
    {
        $user = User::find($id);
        $user->name = $request->get('name');
        $user->password = $request->get('password');
        $user->age = $request->get('age');

        $user->save();
        return new RedirectResponse('/user');
    }

    //删除操作
    public function delete($id)
    {
        User::destroy($id);

        return new JsonResponse([
            'state' => 'ok',
            'message' => '删除成功',
        ]);
    }
}